package cn.sh.yhk.service.basic.impl;

import cn.sh.yhk.mapper.basic.SMenuMapper;
import cn.sh.yhk.mapper.basic.SRoleMapper;
import cn.sh.yhk.model.basic.SMenu;
import cn.sh.yhk.model.basic.SRole;
import cn.sh.yhk.service.basic.MenuService;
import cn.sh.yhk.vo.BasicVo;
import cn.sh.yhk.vo.SMenuVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: adminyhk
 * @Date: 2018/9/26 08:44
 * @Description:
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    SMenuMapper sMenuMapper;

    @Resource
    SRoleMapper sRoleMapper;

    @Override
    public BasicVo getMenuListByUserId(Long userId) {
        List<SMenu> sMenus = new ArrayList<>();
        for (SRole sRole : sRoleMapper.selectRoleByUserId(userId)) {
            sMenus.addAll(sMenuMapper.selectMenuByRoleId(sRole.getId().longValue()));
        }
        List<SMenuVo> parentMenuVos = new ArrayList<>();
        for (SMenu menu : sMenus) {
            SMenuVo tmpvo = new SMenuVo();
            if (menu.getParentId() == 0) {
                BeanUtils.copyProperties(menu, tmpvo);
                parentMenuVos.add(tmpvo);
            }
        }
        for (SMenuVo sMenuVo : parentMenuVos) {
            List<SMenu> childmenus = new ArrayList<>();
            for (SMenu menu : sMenus) {
                if (menu.getParentId().equals(sMenuVo.getId())) {
                    childmenus.add(menu);
                }
            }
            sMenuVo.setsMenuList(new ArrayList<>(childmenus));
        }
        return BasicVo.success(parentMenuVos.stream().sorted(Comparator.comparing(SMenuVo::getMenuSort)).collect(Collectors.toList()));
    }

}
